package tech.yqyl.solo;

import cn.hutool.core.text.StrFormatter;
import tech.yqyl.StringUtil;
import tech.yqyl.solo.processor.AggregationProcessor;
import tech.yqyl.solo.processor.MetaConfig;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

public class ArticleSeries {
    private BlogProcessor sourceProcessor;
    private BlogProcessor targetProcessor;

    public ArticleSeries(String topicName, String basePath) {
        this.basePath = basePath;
        this.topicName = topicName;
        sourceProcessor = new AggregationProcessor(MetaConfig.sourceConfig());
        targetProcessor = new AggregationProcessor(MetaConfig.toHaloNoRightConfig());
    }
    private String basePath;
    /**
     * 是否添加关注
     */
    private String topicName;
    private Map</* blog.oId */String, BlogInfo> blogs = new HashMap<>();

    public void stack(String categories, Article article) {
        blogs.put(article.getOId(), new BlogInfo( categories, article, null));
    }

    /**
     * 将 博客系统 文件写入磁盘
     */
    public void store(){
        // 遍历写入文档
        StringBuffer seriesBuffer = new StringBuffer(StrFormatter.format("# {}\n",topicName));
        blogs.keySet().stream().sorted().forEach(oId->{
            BlogInfo blog = blogs.get(oId);
            String writeFilePath = StrFormatter.format("{}/{}/{}.md",basePath, topicName,oId);
            sourceProcessor.process(blog);
            StringUtil.writeMarkdown(writeFilePath, blog.getArticle().getArticleContent());
            seriesBuffer.append(StrFormatter.format("## [{}]({})\n", blog.getArticle().getArticleTitle(), createLink(oId)));
        });
        String writeSeriesFilePath = StrFormatter.format("{}/{}/README.md", basePath, topicName);
        // 写入系列文章的 README 文件
        StringUtil.writeMarkdown(writeSeriesFilePath, seriesBuffer.toString());
    }

    private String createLink(String linkId) {
        return StrFormatter.format("./{}.md", linkId);
    }


}
